package com.example.dangerouscargodriver.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.entry.PublishInfo;
import com.example.dangerouscargodriver.entry.ReckonInfo;
import com.example.dangerouscargodriver.module.ResourceRecordInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.utils.TextUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.widget.LoadingDialog;
import com.example.dangerouscargodriver.widget.ModifyPriceBottomDialog;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class PublishResourceStepTwoActivity extends HttpRequestActivity implements View.OnClickListener{

    private static final String TAG = "PublishResource";
    private static final int RESPONSE_GET_RECKON_INFO = 0;

    private ActionBar mActionBar = null;
    private TextView mProtocol = null;
    private TextView mAmountOfMoney = null;
    private TextView mOfflineSelector = null;
    private TextView mOnlineSelector = null;
    private TextView mOfflineProtocol = null;

    private TextView mGiveBackSelector = null;
    private TextView mNotGiveBackSelector = null;
    private TextView mDepositNull = null;
    private EditText mDeposit = null;
    private TextView mPublishInfoAction = null;
    private EditText mContact = null;
    private EditText mMobilephone = null;
    private TextView mTruckClassMeta = null;
    private TextView mTruckType = null;
    private TextView mNeedToPay = null;
    private CheckBox mGentleman = null;
    private CheckBox mLady = null;
    private TextView mStartAddress = null;
    private TextView mEndAddress  = null;
    private LinearLayout mOnlineNeedView = null;
    private LinearLayout mOfflineNeedView = null;
    private TextView mMoneyModify = null;
    private TextView mSourceDistance = null;
    private EditText mCommentInfo = null;
    private TextView mCommentHD = null;
    private TextView mCommentFP = null;
    private TextView mCommentUnloadTwo = null;
    private TextView mCommentUnloadMulti = null;

    private ResourceRecordInfo mRecordInfo = null;
    private HomeHandler mHandler = null;
    private ReckonInfo mReckonInfo = null;
    private int mPayType = 2; //1： 线下支付 2：线上支付
    private int mSex = 1; //0：女  1：男
    private PublishInfo mPublishInfo = null;
    private boolean mProtocolAgreed = false;
    private LoadingDialog mLoadingDialog = null;

    private boolean mHDContain = false;
    private boolean mFPContain = false;
    private boolean mUnloadTwoContain = false;
    private boolean mUnloadMultiContain = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(PublishResourceStepTwoActivity.class);
        setContentView(R.layout.activity_publish_resource_step_two);
        AppManager.getAppManager().addActivity(this);

        mLoadingDialog = new LoadingDialog(this);
        //获取传递过来的数据结构
        mRecordInfo = (ResourceRecordInfo)getIntent().getSerializableExtra("info");

        //初始化页面元素
        mProtocol = findViewById(R.id.tv_protocol);
        mAmountOfMoney = findViewById(R.id.tv_amount_of_money);

        mOfflineSelector = findViewById(R.id.tv_pay_offline_selector);
        mOfflineSelector.setOnClickListener(this);
        mOfflineProtocol = findViewById(R.id.tv_pay_offline_protocol);
        mOnlineSelector = findViewById(R.id.tv_pay_online_selector);
        mOnlineSelector.setOnClickListener(this);
        mGiveBackSelector = findViewById(R.id.tv_deposit_giveback);
        mGiveBackSelector.setOnClickListener(this);
        mNotGiveBackSelector = findViewById(R.id.tv_deposit_not_giveback);
        mNotGiveBackSelector.setOnClickListener(this);
        mDepositNull = findViewById(R.id.tv_deposit_null);
        mDepositNull.setOnClickListener(this);

        mDeposit = findViewById(R.id.ed_deposit);
        mPublishInfoAction = findViewById(R.id.btn_publish_info);
        mPublishInfoAction.setOnClickListener(this);
        mContact = findViewById(R.id.ed_contact);
        mMobilephone = findViewById(R.id.ed_mobilephone);
        mTruckClassMeta = findViewById(R.id.tv_truck_class);
        mTruckType = findViewById(R.id.tv_truck_type);
        mNeedToPay = findViewById(R.id.tv_need_to_pay);
        mGentleman = findViewById(R.id.ck_gentleman);
        mLady = findViewById(R.id.ck_lady);
        mMoneyModify = findViewById(R.id.text_money_modify);
        mGentleman.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mLady.setChecked(false);
                }
                else{
                    mLady.setChecked(true);
                }
            }
        });
        mLady.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mGentleman.setChecked(false);
                }
                else{
                    mGentleman.setChecked(true);
                }
            }
        });
        mStartAddress = findViewById(R.id.tv_start_address);
        mEndAddress = findViewById(R.id.tv_end_address);
        mMoneyModify = findViewById(R.id.text_money_modify);
        mMoneyModify.setOnClickListener(this);

        mCommentHD = findViewById(R.id.tv_comment_hd);
        mCommentHD.setOnClickListener(this);
        mCommentFP = findViewById(R.id.tv_comment_fp);
        mCommentFP.setOnClickListener(this);
        mCommentUnloadTwo = findViewById(R.id.tv_comment_unload_two);
        mCommentUnloadTwo.setOnClickListener(this);
        mCommentUnloadMulti = findViewById(R.id.tv_comment_unload_multi);
        mCommentUnloadMulti.setOnClickListener(this);
        mCommentInfo = findViewById(R.id.tv_comment_info);

        //填充页面资源
        mTruckClassMeta.setText(mRecordInfo.getTruck_cname());
        mTruckType.setText(mRecordInfo.getTruck_type()+"：");
        mStartAddress.setText(mRecordInfo.getFrom_address());
        mEndAddress.setText(mRecordInfo.getTo_address());
        if(mRecordInfo.getContact() != "") {
            mContact.setText(mRecordInfo.getContact());
        }
        if(mRecordInfo.getMobliephone() != null){
            mMobilephone.setText(mRecordInfo.getMobliephone());
        }

        TextUtils.getBuilder().click(getResources().getString(R.string.pay_offline_protocol), getResources().getColor(R.color.liji_c_blue), new TextUtils.OnClickListener() {
            @Override
            public void onClick(int position) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(PublishResourceStepTwoActivity.this, ShowHtmlActivity.class);
                        intent.putExtra("type", "1");
                        startActivity(intent);
                        break;
                }
            }
        }, "《危司机平台订金担保规则》").clickInto(mOfflineProtocol);

        TextUtils.getBuilder().click(getResources().getString(R.string.company_partner_protocol_order), getResources().getColor(R.color.liji_c_blue), new TextUtils.OnClickListener() {
            @Override
            public void onClick(int position) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(PublishResourceStepTwoActivity.this, ShowHtmlActivity.class);
                        intent.putExtra("type", "3");
                        startActivity(intent);
                        break;
                    case 1:
                        Intent intent1 = new Intent(PublishResourceStepTwoActivity.this, ShowHtmlActivity.class);
                        intent1.putExtra("type", "2");
                        startActivity(intent1);
                        break;
                    case 2:
                        Intent intent2 = new Intent(PublishResourceStepTwoActivity.this, ShowHtmlActivity.class);
                        intent2.putExtra("type", "1");
                        startActivity(intent2);
                        break;
                    default:
                        break;
                }
            }
        }, "《危司机用户服务协议》", "《危司机隐私政策》", "《危司机平台订金担保规则》").checkBox(this,  mProtocol, new TextUtils.OnImageClickListener() {
            @Override
            public void onChecked() {
                mProtocolAgreed = true;
            }

            @Override
            public void onUnChecked() {
                mProtocolAgreed = false;
            }
        }).clickInto(mProtocol);

        //默认线上支付
        mOnlineNeedView = findViewById(R.id.layout_online_need);
        mOfflineNeedView = findViewById(R.id.layout_offline_need);
        mOfflineNeedView.setVisibility(View.GONE);
        mOnlineNeedView.setVisibility(View.VISIBLE);
        mGiveBackSelector.setVisibility(View.VISIBLE);
        mGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
        mNotGiveBackSelector.setVisibility(View.GONE);

        mSourceDistance = findViewById(R.id.tv_source_distance);

        mActionBar = findViewById(R.id.actionBarPublicResourceStepTwo);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        init();

        //执行估价的操作
        String[] cid = mRecordInfo.getTruck_cid().split(",");
        HashMap<String, String> resource_param = new HashMap<String, String>();
        resource_param.put("goid", mRecordInfo.getFrom_address_id().substring(
                mRecordInfo.getFrom_address_id().indexOf("-") + 1,
                mRecordInfo.getFrom_address_id().indexOf("-") + 7)
        );
        Log.d(TAG, "resource_param: " + resource_param.toString());
        resource_param.put("toid", mRecordInfo.getTo_address_id().substring(
                mRecordInfo.getTo_address_id().indexOf("-") + 1,
                mRecordInfo.getTo_address_id().indexOf("-") + 7)
        );
        resource_param.put("truckid", cid[0]);
        resource_param.put("heft", mRecordInfo.getWeight());
        resource_param.put("goodstype", mRecordInfo.getClass_id());
        resource_param.put("goTownid", mRecordInfo.getFrom_address_id().substring(
                mRecordInfo.getFrom_address_id().lastIndexOf("-") + 1,
                mRecordInfo.getFrom_address_id().lastIndexOf("-") + 7)
        );
        resource_param.put("toTownid", mRecordInfo.getTo_address_id().substring(
                mRecordInfo.getTo_address_id().lastIndexOf("-") + 1,
                mRecordInfo.getTo_address_id().lastIndexOf("-") + 7)
        );

        //填入一些已存在的信息
        if(UserInfoController.Instance().getUserInfo() != null) {
            mMobilephone.setText(UserInfoController.Instance().getUserInfo().getMobilephone());
        }
        sendHttpRequest(
            IHttpRequest.RequestMethod.GET_METHOD,
            RemoteAPI.REQUEST_V1_ABACUS_RECKON,
            null,
            resource_param,
            RemoteAPICmd.REQUEST_V1_ABACUS_RECKON);
    }

    private void init(){
        mHandler = new HomeHandler(this);
    }

    private void fillResourceRecordInfo(){
        mRecordInfo.setExpected_price(mReckonInfo.getTotal());
        mRecordInfo.setSource_distance(mReckonInfo.getDistance());
    }

    private void refreshReckonInfo(){
        mAmountOfMoney.setText(mReckonInfo.getTotal());
        mNeedToPay.setText(mReckonInfo.getTotal());
        mSourceDistance.setText(mReckonInfo.getDistance() + "公里");
    }

    private void publishRecordInfo(){
        //执行发布货源的操作
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        HashMap<String, String> resource_param = new HashMap<String, String>();
        resource_param.put("class_id", mRecordInfo.getClass_id());
        resource_param.put("weight", mRecordInfo.getWeight());
        resource_param.put("from_id", mRecordInfo.getFrom_address_id());
        resource_param.put("to_id", mRecordInfo.getTo_address_id());
        resource_param.put("truck_cid", mRecordInfo.getTruck_cid());
        resource_param.put("contact", mContact.getText().toString());
        resource_param.put("mobilephone", mMobilephone.getText().toString());
        resource_param.put("source_distance", mRecordInfo.getSource_distance());
        resource_param.put("expected_price", mRecordInfo.getExpected_price());
        resource_param.put("pay_type", Integer.toString(mPayType));
        if(mGentleman.isChecked()){
            resource_param.put("contact_sex", "1");
        }
        else{
            resource_param.put("contact_sex", "0");
        }
        if(mDeposit.getText().toString().equals("")){
            resource_param.put("deposit", "0.00");
        }
        else {
            resource_param.put("deposit", mDeposit.getText().toString());
        }
        resource_param.put("loadtime", mRecordInfo.getLoadtime());
        if(mRecordInfo.getLoadtime2() != null &&
                !mRecordInfo.getLoadtime2().equals(mRecordInfo.getLoadtime())){
            resource_param.put("loadtime2", mRecordInfo.getLoadtime2());
        }
        if(mCommentInfo.getText().toString() != null){
            resource_param.put("remark", mCommentInfo.getText().toString());
        }

        mLoadingDialog.show();

        Log.d(TAG, "resource_param: " + resource_param.toString());
        sendHttpRequest(
            IHttpRequest.RequestMethod.POST_METHOD,
            RemoteAPI.REQUEST_V1_SG_SOURCE_GOODS,
            header,
            resource_param,
            RemoteAPICmd.REQUEST_V1_SG_SOURCE_GOODS);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private boolean checkInput(){
        if(mContact.getText().toString() == null ||
                mContact.getText().toString().equals("") ||
                mMobilephone.getText().toString() == null ||
                mMobilephone.getText().toString().equals("")){
            return false;
        }
        else{
            return true;
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.tv_pay_offline_selector){
            if(mPayType == 2){
                v.setBackgroundResource(R.drawable.rounded_button);
                mOnlineSelector.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mPayType = 1;
            }
            else{
                v.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mOnlineSelector.setBackgroundResource(R.drawable.rounded_button);
                mPayType = 2;
            }
            mOfflineProtocol.setVisibility(View.VISIBLE);
            mOfflineNeedView.setVisibility(View.VISIBLE);
            mGiveBackSelector.setVisibility(View.GONE);
            mNotGiveBackSelector.setVisibility(View.VISIBLE);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mOnlineNeedView.setVisibility(View.GONE);
        }
        else if(v.getId() == R.id.tv_pay_online_selector){
            if(mPayType == 2){
                v.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mOfflineSelector.setBackgroundResource(R.drawable.rounded_button);
                mPayType = 1;
            }
            else{
                v.setBackgroundResource(R.drawable.rounded_button);
                mOfflineSelector.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mPayType = 2;
            }
            mOfflineProtocol.setVisibility(View.GONE);
            mOfflineNeedView.setVisibility(View.GONE);
            mOnlineNeedView.setVisibility(View.VISIBLE);
            mGiveBackSelector.setVisibility(View.VISIBLE);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mNotGiveBackSelector.setVisibility(View.GONE);
        }
        else if(v.getId() == R.id.tv_deposit_giveback){
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mDeposit.setHint(R.string.item_front_money_num);
            mDeposit.setEnabled(true);
        }
        else if(v.getId() == R.id.tv_deposit_not_giveback){
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mDeposit.setHint(R.string.item_front_money_num);
            mDeposit.setEnabled(true);
        }
        else if(v.getId() == R.id.tv_deposit_null){
            mDepositNull.setBackgroundResource(R.drawable.rounded_button);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mDeposit.setText("");
            mDeposit.setHint("");
            mDeposit.setEnabled(false);
        }
        else if(v.getId() == R.id.btn_publish_info){
            if(!mProtocolAgreed){
                ToastUtils.showLongToast(this, "请查看并同意相关的服务协议!");
                return;
            }
            if(checkInput()) {
                publishRecordInfo();
            }
            else{
                ToastUtils.showLongToast(this, "请填写完整的发布信息！");
            }
        }
        else if(v.getId() == R.id.text_money_modify){
            ModifyPriceBottomDialog dialog = new ModifyPriceBottomDialog();
            dialog.setOnItemClickListener(new ModifyPriceBottomDialog.OnItemClickListener() {
                @Override
                public void onConfirm(String price) {
                    if(price!= null && !price.equals("")) {
                        mAmountOfMoney.setText(price);
                        mNeedToPay.setText(price);
                    }
                }

                @Override
                public void onCancel() {

                }
            });
            dialog.showDialog(this);
        }
        else if(v.getId() == R.id.tv_comment_hd){
            if(mHDContain){
                String mark = mCommentInfo.getText().toString();
                if(mark.contains("需要回单")){
                    mark = mark.replace("需要回单", "");
                    mCommentInfo.setText(mark);
                }
                mHDContain = false;
                mCommentHD.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
            }
            else{
                String mark = mCommentInfo.getText().toString();
                mark += "需要回单";
                mCommentInfo.setText(mark);
                mHDContain = true;
                mCommentHD.setBackgroundResource(R.drawable.rounded_button);
            }
        }
        else if(v.getId() == R.id.tv_comment_fp){
            if(mFPContain){
                String mark = mCommentInfo.getText().toString();
                if(mark.contains("需要发票")){
                    mark = mark.replace("需要发票", "");
                    mCommentInfo.setText(mark);
                }
                mFPContain = false;
                mCommentFP.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
            }
            else{
                String mark = mCommentInfo.getText().toString();
                mark += "需要发票";
                mCommentInfo.setText(mark);
                mFPContain = true;
                mCommentFP.setBackgroundResource(R.drawable.rounded_button);
            }
        }
        else if(v.getId() == R.id.tv_comment_unload_two){
            if(mUnloadTwoContain){
                String mark = mCommentInfo.getText().toString();
                if(mark.contains("一装两卸")){
                    mark = mark.replace("一装两卸", "");
                    mCommentInfo.setText(mark);
                }
                mUnloadTwoContain = false;
                mCommentUnloadTwo.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
            }
            else{
                String mark = mCommentInfo.getText().toString();
                mark += "一装两卸";
                mCommentInfo.setText(mark);
                mUnloadTwoContain = true;
                mCommentUnloadTwo.setBackgroundResource(R.drawable.rounded_button);
            }
        }
        else if(v.getId() == R.id.tv_comment_unload_multi){
            if(mUnloadMultiContain){
                String mark = mCommentInfo.getText().toString();
                if(mark.contains("一装多卸")){
                    mark = mark.replace("一装多卸", "");
                    mCommentInfo.setText(mark);
                }
                mUnloadMultiContain = false;
                mCommentUnloadMulti.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
            }
            else{
                String mark = mCommentInfo.getText().toString();
                mark += "一装多卸";
                mCommentInfo.setText(mark);
                mUnloadMultiContain = true;
                mCommentUnloadMulti.setBackgroundResource(R.drawable.rounded_button);
            }
        }
        else{
            /**/
        }
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V1_ABACUS_RECKON){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    JSONObject data = res.getJSONObject("data");
                    mReckonInfo = gson.fromJson(data.toString(), ReckonInfo.class);
                    refreshReckonInfo();
                    fillResourceRecordInfo();
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_V1_SG_SOURCE_GOODS){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    //发布货源成功
                    PublishInfo publishInfo = gson.fromJson(res.get("data").toString(), PublishInfo.class);
                    Intent intent = new Intent(this, PublishResourceSuccessActivity.class);
                    intent.putExtra("info", publishInfo);
                    startActivity(intent);
                }
                else{
                    //发布货源失败
                    ToastUtils.showLongToast(getBaseContext(), res.getString("message"));
                }
                mLoadingDialog.dismiss();
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V1_SG_SOURCE_GOODS){
            mLoadingDialog.dismiss();
        }
        else{

        }
    }

    private static class HomeHandler extends Handler {
        private String TAG = "HomeHandler";
        private final WeakReference<PublishResourceStepTwoActivity> mActivity;

        HomeHandler(PublishResourceStepTwoActivity activity) {
            mActivity = new WeakReference<PublishResourceStepTwoActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            PublishResourceStepTwoActivity activity = mActivity.get();
            switch (msg.what){
                default:
                    break;
            }
        }
    }
}